#!/usr/bin/python
# -*- coding:utf-8 -*-
# -------------------------------------------------------
# @author  : 龍皓
# @time    : 2025/3/10 21:21
# @function: 文件操作工具类。
# @version : 1.0.0
# -------------------------------------------------------
import csv
import json
import yaml
from core.util.logger import setup_logger

logger = setup_logger()

class FileUtil:
    @staticmethod
    def read_yaml_file(file_path):
        """从指定路径读取YAML文件"""
        encodings = ['utf-8', 'gbk', 'gb2312']
        for encoding in encodings:
            try:
                with open(file_path, 'r', encoding=encoding) as file:
                    config = yaml.safe_load(file)
                    logger.info(f"Successfully loaded YAML from {file_path}")
                    return config
            except UnicodeDecodeError:
                continue
            except Exception as e:
                logger.error(f"Failed to load YAML from {file_path}: {e}")
        raise Exception("Failed to decode the file with provided encodings")

    @staticmethod
    def write_yaml_file(file_path, data):
        """将数据写入指定路径的YAML文件"""
        try:
            with open(file_path, 'w', encoding='utf-8') as file:
                yaml.safe_dump(data, file, default_flow_style=False, allow_unicode=True)
                logger.info(f"Successfully wrote YAML to {file_path}")
        except Exception as e:
            logger.error(f"Failed to write YAML to {file_path}: {e}")

    @staticmethod
    def export_yaml(file_path, data, default_flow_style=False, allow_unicode=True):
        """
        将数据导出为YAML文件
        参数：
            file_path: 文件路径
            data: 要导出的数据
            default_flow_style: 默认流样式，默认为False
            allow_unicode: 允许Unicode，默认为True
        """
        try:
            with open(file_path, 'w', encoding='utf-8') as file:
                yaml.safe_dump(data, file, default_flow_style=default_flow_style, allow_unicode=allow_unicode)
                logger.info(f"成功导出YAML文件：{file_path}")
        except Exception as e:
            logger.error(f"导出YAML文件失败：{str(e)}")

    @staticmethod
    def read_json_file(file_path):
        """从指定路径读取JSON文件"""
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                data = json.load(file)
                logger.info(f"Successfully loaded JSON from {file_path}")
                return data
        except FileNotFoundError:
            logger.error(f"File not found at {file_path}")
            return None
        except json.JSONDecodeError as e:
            logger.error(f"Failed to decode JSON from {file_path}: {e}")
            return None

    @staticmethod
    def write_json_file(file_path, data):
        """将数据写入指定路径的JSON文件"""
        try:
            with open(file_path, 'w', encoding='utf-8') as file:
                json.dump(data, file, indent=4, ensure_ascii=False)
                logger.info(f"Successfully wrote JSON to {file_path}")
        except Exception as e:
            logger.error(f"Failed to write JSON to {file_path}: {e}")

    @staticmethod
    def export_json(file_path, data, indent=4, ensure_ascii=False):
        """
        将数据导出为JSON文件
        参数：
            file_path: 文件路径
            data: 要导出的数据
            indent: 缩进量，默认为4
            ensure_ascii: 是否确保ASCII编码，默认为False
        """
        try:
            with open(file_path, 'w', encoding='utf-8') as file:
                json.dump(data, file, indent=indent, ensure_ascii=ensure_ascii)
                logger.info(f"成功导出JSON文件：{file_path}")
        except Exception as e:
            logger.error(f"导出JSON文件失败：{str(e)}")

    @staticmethod
    def read_csv(file_path, encoding='utf-8-sig', delimiter=','):
        """
        读取CSV文件为字典列表
        参数：
            file_path: 文件路径
            encoding: 文件编码 (默认使用utf-8-sig处理Excel生成的CSV)
            delimiter: 分隔符 (默认逗号)
        返回：
            list[dict] 字典列表
        """
        try:
            with open(file_path, 'r', encoding=encoding) as file:
                reader = csv.DictReader(file, delimiter=delimiter)
                return [row for row in reader]
        except FileNotFoundError:
            logger.error(f"CSV文件不存在：{file_path}")
            return None
        except Exception as e:
            logger.error(f"读取CSV文件失败：{str(e)}")
            return None

    @staticmethod
    def write_csv(file_path, data, headers=None, encoding='utf-8-sig', delimiter=','):
        """
        写入数据到CSV文件
        参数：
            file_path: 文件路径
            data: 要写入的数据（字典列表）
            headers: 自定义表头（默认使用数据第一个字典的键）
            encoding: 文件编码
            delimiter: 分隔符
        """
        if not data:
            logger.warning("尝试写入空数据到CSV文件")
            return

        try:
            with open(file_path, 'w', encoding=encoding, newline='') as file:
                # 自动获取表头（如果未指定）
                fieldnames = headers or list(data[0].keys())

                writer = csv.DictWriter(
                    file,
                    fieldnames=fieldnames,
                    delimiter=delimiter
                )
                writer.writeheader()
                writer.writerows(data)
            logger.info(f"成功写入CSV文件：{file_path}")
        except Exception as e:
            logger.error(f"写入CSV文件失败：{str(e)}")

    @staticmethod
    def export_csv(file_path, data, headers=None, encoding='utf-8-sig'):
        """
        导出数据到CSV文件（兼容中文的增强版）
        参数：
            file_path: 文件路径
            data: 要导出的数据（二维列表或字典列表）
            headers: 表头列表（可选）
            encoding: 文件编码
        """
        try:
            with open(file_path, 'w', encoding=encoding, newline='') as file:
                writer = csv.writer(file)

                if isinstance(data[0], dict):  # 如果是字典列表
                    headers = headers or list(data[0].keys())
                    writer.writerow(headers)
                    for item in data:
                        writer.writerow([item.get(col, '') for col in headers])
                else:  # 如果是二维列表
                    if headers:
                        writer.writerow(headers)
                    writer.writerows(data)

            logger.info(f"成功导出CSV文件：{file_path}")
        except Exception as e:
            logger.error(f"导出CSV文件失败：{str(e)}")



